import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import LoginVue from "../view/login/index.vue";
import HomeVue from "../view/home/index.vue";
import { userInfoApi } from "@/http/api";
import { useUserStore } from "@/store/user";
import { ElMessage } from "element-plus";
const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    component: LoginVue,
  },
  {
    path: "/",
    component: () => import("../view/home/index.vue"),
    children: [
      {
        path: "index",
        component: () => import("../view/index/index.vue"),
      },
    ],
  },
];

const router = createRouter({
  routes,
  history: createWebHashHistory(),
});

router.beforeEach((to, from, next) => {
  const store = useUserStore();
  let token = localStorage.getItem("token");
  if (store.menus.length === 0 && token) {
    userInfoApi().then((res) => {
      if (res.code === 200) {
        store.menus = res.data.menus;
        store.username = res.data.username;
        store.routes.forEach((item) => {
          const route: RouteRecordRaw = {
            path: "/" + item.name,
            component: () => import("../view/home/index.vue"),
            meta: {
              title: item.title,
            },
            redirect: `/${item.name}/${item.children[0]?.name}`,
            children: item.children.map((sub) => ({
              path: sub.name,
              name: sub.name,
              component: () => import(`../view/${item.name}/${sub.name}.vue`),
              meta: {
                title: sub.title,
              },
            })),
          };
          if (item.children[0]) {
            route.redirect = `/${item.name}/${item.children[0]?.name}`;
          }
          router.addRoute(route);
        });
        next(to.fullPath);
      }
    });
  } else if (token && store.menus.length !== 0 && to.path === "/login") {
    ElMessage.warning("请先退出登录再重新登录");
    next(from.fullPath);
  } else {
    next();
  }
});

export default router;
